
const {findType} = require('../service/type.service')

const {
  typeFormateError,
  typeIdFormateError,
  typeDoesNotExist,
  typeAlreadyExited,
  typeInsertError
} = require('../constant/err.type')

// 验证类型是否为空
const typeValidator = async (ctx, next) => {
  const {type_name} = ctx.request.body;
  if(!type_name) {
    console.error('类型名为空', ctx.request.body)
    ctx.response.body = typeFormateError
    return
  }
  await next()
}

// 验证类型id是否为空
const typeIdValidator = async (ctx, next) => {
  const {id} = ctx.request.body;
  if(!id) {
    ctx.response.body = typeIdFormateError
    return
  }
  await next()
}

// 验证类型id是不存在
const hasNotType = async (ctx, next) => {
  const {id} = ctx.request.body;
  try {
    const res = await findType({id})
    if(!res || res.length === 0 ) {
      console.error('不存在此类型id', ctx.request.body)
      ctx.response.body = typeDoesNotExist
      return
    }
  } catch(err) {
    console.log('获取类型信息错误', err)
    ctx.response.body = typeInsertError
    return
  }
  await next()
}

// 验证类型是否为空
const hasType = async (ctx, next) => {
  const {type_name} = ctx.request.body;

  try {
    const res = await findType({type_name})
    if(res && res.length > 0) {
      console.error('该类型已经存在，请勿重复添加！', ctx.request.body)
      ctx.response.body = typeAlreadyExited
      return
    } 
  } catch(err) {
    console.error('获取类型信息错误', err)
    ctx.response.body = typeInsertError
    return
  }
  await next()
}

module.exports = {typeValidator, typeIdValidator, hasType, hasNotType}